//
//  TravelNotesDetailViewController.swift
//  TravelNotes
//
//  Created by 千锋 on 16/8/18.
//  Copyright © 2016年 胡光健. All rights reserved.
//

import UIKit

class TravelNotesDetailViewController: RootViewController, UITableViewDataSource, UITableViewDelegate {

    var model = TravelNotesModel()
    var tableView = UITableView()
    var headerImageView = UIImageView()
    let imageOriginaHeight: CGFloat = 200.0
    var dataArray = NSMutableArray()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.whiteColor()
        createNav()
        createUI()
        getData()
        
    }
    func getData() {
        
        let manager = AFHTTPSessionManager()
        manager.responseSerializer.acceptableContentTypes = NSSet(object: "text/html") as! Set<String>
        let str = "http://chanyouji.com/api/trips/\((model.id)!).json"
        print(str)
        let url = NSURL(string: str)
        let request = NSURLRequest(URL: url!)
        manager.securityPolicy.allowInvalidCertificates = true
        manager.securityPolicy.validatesDomainName = false
        let dataTask = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, resp, error) -> Void in
            let str1 = NSString(data: data!, encoding: NSUTF8StringEncoding)
            do {
                let dic = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
                self.headerImageView.sd_setImageWithURL(NSURL(string: dic.objectForKey("front_cover_photo_url") as! String), placeholderImage: UIImage(named: ""))
                let arr = dic.objectForKey("trip_days") as! NSArray
                for dic in arr {
                    let subArr1 = dic.objectForKey("nodes") as! NSArray
                    for subDic in subArr1 {
                        let array = subDic.objectForKey("notes") as! NSArray
                        let tempArr = NSMutableArray()
                        for sub in array {
                            //字典转模型
                            let travelNotesDetailModel = TravelNotesDetailModel()
                            travelNotesDetailModel.setValuesForKeysWithDictionary(sub as! [String : AnyObject])
                            
                            //将模型添加到tempArr
                            tempArr.addObject(travelNotesDetailModel)
//                            if sub["photo"] != nil {
//                                let photo = sub.objectForKey("photo") as! [String: AnyObject]
//                                tempArr.addObject(photo)
//                            }
                        }
                        //将tempArr添加dataArray
                        self.dataArray.addObjectsFromArray(tempArr as [AnyObject])
                    }
                }
                //刷新数据
                self.tableView.reloadData()
            }
            catch {
                
            }
        }
            
        dataTask.resume()
        
    }
    
    func createUI() {
        tableView = UITableView(frame: CGRectMake(0, 0, screenWidth, screenHeight), style: .Plain)
        tableView.tableFooterView = UIView()
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableViewAutomaticDimension
//        tableView.separatorColor = UIColor.RGBA(85, 164, 154)
        tableView.delegate = self
        tableView.dataSource = self
        self.view.addSubview(tableView)
       
        headerImageView = Factory.createImageViewWith(CGRectMake(0, -imageOriginaHeight, screenWidth, imageOriginaHeight), imageName: "")
        self.tableView.addSubview(headerImageView)
        self.tableView.tableHeaderView = headerImageView
        
       
        tableView.registerNib(UINib(nibName: "TravelNotesDetailCell", bundle: nil), forCellReuseIdentifier: "travelNotesDetailCell")
        tableView.registerNib(UINib(nibName: "TravelCell", bundle: nil), forCellReuseIdentifier: "travelCell")
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if (dataArray[indexPath.row].valueForKey("photo") == nil) {
            let cell = tableView.dequeueReusableCellWithIdentifier("travelNotesDetailCell", forIndexPath: indexPath) as! TravelNotesDetailCell
            cell.model = self.dataArray[indexPath.row] as! TravelNotesDetailModel
            return cell
        } else {
            let cell = tableView.dequeueReusableCellWithIdentifier("travelCell", forIndexPath: indexPath) as! TravelCell
            cell.travelModel = self.dataArray[indexPath.row] as! TravelNotesDetailModel
            return cell
        }
        
//        if dataArray.count > 0 {
//            cell.model = self.dataArray[indexPath.row] as! TravelNotesDetailModel
//        }
        
        
    }
    
    func createNav() {
        
        self.leftButton?.setImage(UIImage(named: "BackBarButton"), forState: .Normal)
        self.rightBuuton?.setImage(UIImage(named: "shoucang1"), forState: .Normal)
        self.leftButton?.addTarget(self, action: "backButtonClicked", forControlEvents: .TouchUpInside)
        self.rightBuuton?.addTarget(self, action: "collectButtonClicked", forControlEvents: .TouchUpInside)
    }
    
    func backButtonClicked() {
        self.navigationController?.popViewControllerAnimated(true)
    }
    
    func collectButtonClicked() {
        
    }
}
